class TargetScoreForm {
    constructor() {
        this.form = document.getElementById('targetScoreForm');
        this.subjectSelect = document.getElementById('subject-category-select');
        this.regionAdjustment = 0;
        this.init();
    }

    init() {
        this.addInputStyling();
        this.bindEvents();
        this.updateScorePreview();
        this.updateConfidenceVisual();
        this.updateProgressVisual();
    }

    // 为输入框添加自定义样式
    addInputStyling() {
        const inputs = document.querySelectorAll('input, textarea, select');
        inputs.forEach(input => {
            if (!input.classList.contains('form-control-custom') &&
                !input.classList.contains('btn')) {
                input.classList.add('form-control-custom');
            }
        });
    }

    // 绑定事件监听器
    bindEvents() {
        // 科目选择变化事件
        if (this.subjectSelect) {
            this.subjectSelect.addEventListener('change', () => this.onSubjectChange());
        }

        // 分数输入框变化事件
        const scoreInputs = document.querySelectorAll('.score-input');
        scoreInputs.forEach(input => {
            input.addEventListener('input', () => this.updateScorePreview());
        });

        // 信心指数变化事件
        const confidenceInput = document.getElementById('id_confidence_level');
        if (confidenceInput) {
            confidenceInput.addEventListener('input', () => this.updateConfidenceVisual());
        }

        // 进度变化事件
        const progressInput = document.getElementById('id_overall_progress');
        if (progressInput) {
            progressInput.addEventListener('input', () => this.updateProgressVisual());
        }

        // 表单提交事件
        if (this.form) {
            this.form.addEventListener('submit', (e) => this.handleSubmit(e));
        }
    }

    // 科目变化处理
    onSubjectChange() {
        this.calculateRegionAdjustment();
        this.updateScorePreview();
    }

    // 计算地域影响调整
    calculateRegionAdjustment() {
        const selectedSubject = this.subjectSelect ? this.subjectSelect.value : '';
        const studentRegion = document.querySelector('.region-content strong')?.textContent.trim() || '其他';

        let adjustment = 0;

        // 政治科目地域影响最大
        if (selectedSubject === 'politics') {
            const regionImpact = {
                '北京': -8,
                '上海': -6,
                '江苏': -4,
                '浙江': -4,
                '湖北': -2,
                '广东': 0,
                '四川': 0,
                '其他': 0
            };
            adjustment = regionImpact[studentRegion] || 0;
        }
        // 英语科目也有轻微地域影响
        else if (selectedSubject === 'english') {
            // 修复：使用 JavaScript 数组
            const strictRegions = ['北京', '上海', '江苏', '浙江'];
            if (strictRegions.includes(studentRegion)) {
                adjustment = -2;
            }
        }

        this.regionAdjustment = adjustment;
        return adjustment;
    }

    // 更新分数预览
    updateScorePreview() {
        const idealInput = document.getElementById('id_ideal_target');
        const realisticInput = document.getElementById('id_realistic_target');
        const safetyInput = document.getElementById('id_safety_target');

        const idealValue = parseFloat(idealInput?.value) || 0;
        const realisticValue = parseFloat(realisticInput?.value) || 0;
        const safetyValue = parseFloat(safetyInput?.value) || 0;

        const adjustment = this.calculateRegionAdjustment();

        // 更新预览显示
        const idealPreview = document.getElementById('idealPreview');
        const realisticPreview = document.getElementById('realisticPreview');
        const safetyPreview = document.getElementById('safetyPreview');

        if (idealPreview) idealPreview.textContent = Math.max(0, idealValue + adjustment);
        if (realisticPreview) realisticPreview.textContent = Math.max(0, realisticValue + adjustment);
        if (safetyPreview) safetyPreview.textContent = Math.max(0, safetyValue + adjustment);
    }

    // 更新信心可视化
    updateConfidenceVisual() {
        const confidenceInput = document.getElementById('id_confidence_level');
        const confidenceFill = document.getElementById('confidenceFill');

        if (confidenceInput && confidenceFill) {
            const value = Math.max(0, Math.min(100, parseInt(confidenceInput.value) || 0));
            confidenceFill.style.width = `${value}%`;

            // 根据信心值改变颜色
            if (value < 30) {
                confidenceFill.style.background = 'linear-gradient(90deg, #ff6b6b, #ee5a52)';
            } else if (value < 70) {
                confidenceFill.style.background = 'linear-gradient(90deg, #feca57, #ff9ff3)';
            } else {
                confidenceFill.style.background = 'linear-gradient(90deg, #48cae4, #4361ee)';
            }
        }
    }

    // 更新进度可视化
    updateProgressVisual() {
        const progressInput = document.getElementById('id_overall_progress');
        const progressFill = document.getElementById('progressFill');

        if (progressInput && progressFill) {
            const value = Math.max(0, Math.min(100, parseInt(progressInput.value) || 0));
            progressFill.style.width = `${value}%`;
        }
    }

    // 处理表单提交
    async handleSubmit(e) {
        e.preventDefault();

        const submitBtn = this.form.querySelector('button[type="submit"]');
        const originalText = submitBtn.innerHTML;

        // 显示加载状态
        this.setButtonLoading(submitBtn, true);

        try {
            const response = await this.submitForm();

            // 检查响应类型
            const contentType = response.headers.get('content-type');
            if (contentType && contentType.includes('application/json')) {
                const data = await response.json();

                if (data.success) {
                    this.showAlert('success', data.message);
                    this.redirectToDetailPage();
                } else {
                    this.showFormErrors(data.errors);
                }
            } else {
                // 如果不是 JSON 响应，可能是传统的表单提交
                this.form.submit();
            }
        } catch (error) {
            console.error('Error:', error);
            this.showAlert('danger', '保存失败，请重试');
        } finally {
            this.setButtonLoading(submitBtn, false, originalText);
        }
    }

    // 设置按钮加载状态
    setButtonLoading(button, isLoading, originalText = '') {
        if (isLoading) {
            button.disabled = true;
            button.innerHTML = '<i class="bi bi-arrow-repeat spinner me-2"></i>保存中...';
        } else {
            button.disabled = false;
            button.innerHTML = originalText;
        }
    }

    // 提交表单数据
    async submitForm() {
        const formData = new FormData(this.form);

        return await fetch(this.form.action, {
            method: 'POST',
            body: formData,
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'X-CSRFToken': this.getCSRFToken()
            }
        });
    }

    // 获取 CSRF token
    getCSRFToken() {
        const csrfInput = document.querySelector('[name=csrfmiddlewaretoken]');
        return csrfInput ? csrfInput.value : '';
    }

    // 显示表单错误
    showFormErrors(errors) {
        // 清除之前的错误
        this.clearFormErrors();

        // 添加新的错误
        if (errors) {
            for (const field in errors) {
                this.addFieldError(field, errors[field]);
            }
        }
    }

    // 清除表单错误
    clearFormErrors() {
        document.querySelectorAll('.is-invalid').forEach(el => {
            el.classList.remove('is-invalid');
        });
        document.querySelectorAll('.invalid-feedback').forEach(el => {
            el.remove();
        });
    }

    // 添加字段错误
    addFieldError(field, errorMessages) {
        const input = document.getElementById(`id_${field}`);
        if (input) {
            input.classList.add('is-invalid');
            const errorDiv = document.createElement('div');
            errorDiv.className = 'invalid-feedback';
            errorDiv.innerHTML = Array.isArray(errorMessages) ? errorMessages.join('<br>') : errorMessages;
            input.parentNode.appendChild(errorDiv);

            // 滚动到第一个错误字段
            if (!this.firstErrorField) {
                this.firstErrorField = input;
                input.scrollIntoView({ behavior: 'smooth', block: 'center' });
            }
        }
    }

    // 显示提示消息
    showAlert(type, message) {
        // 移除现有的提示
        document.querySelectorAll('.alert').forEach(alert => alert.remove());

        const alertDiv = document.createElement('div');
        alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
        alertDiv.innerHTML = `
            <i class="bi bi-${type === 'success' ? 'check-circle' : 'exclamation-triangle'} me-2"></i>
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;

        const container = document.querySelector('.container') || document.querySelector('.target-form-container');
        if (container) {
            container.insertBefore(alertDiv, container.firstChild);

            // 自动消失
            if (type === 'success') {
                setTimeout(() => {
                    if (alertDiv.parentNode) {
                        alertDiv.remove();
                    }
                }, 5000);
            }
        }
    }

    // 跳转到详情页
    redirectToDetailPage() {
        setTimeout(() => {
            const backLink = document.querySelector('.btn-back');
            if (backLink && backLink.href) {
                window.location.href = backLink.href;
            }
        }, 1500);
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    new TargetScoreForm();

    // 初始化显示
    const confidenceInput = document.getElementById('id_confidence_level');
    const progressInput = document.getElementById('id_overall_progress');

    if (confidenceInput && confidenceInput.value) {
        const event = new Event('input');
        confidenceInput.dispatchEvent(event);
    }

    if (progressInput && progressInput.value) {
        const event = new Event('input');
        progressInput.dispatchEvent(event);
    }

    // 如果是在编辑模式，初始化分数预览
    const targetForm = document.getElementById('targetScoreForm');
    if (targetForm) {
        const event = new Event('input');
        targetForm.querySelector('.score-input')?.dispatchEvent(event);
    }
});

// 添加 spinner 动画样式
const style = document.createElement('style');
style.textContent = `
    .spinner {
        animation: spin 1s linear infinite;
    }
    @keyframes spin {
        from { transform: rotate(0deg); }
        to { transform: rotate(360deg); }
    }
`;
document.head.appendChild(style);